﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

using EOH.Sms.Alibaba;
using EOH.Sms.Tencent;

namespace System
{
    /// <summary>IServiceCollection 扩展方法</summary>
    public static class ServiceCollectionExtension
    {
        /// <summary>阿里巴巴短信服务</summary>
        public static IServiceCollection AddAlibabaSmsService(this IServiceCollection service, Action<AlibabaOptions> setupAction)
        {
            if (service is null) { throw new ArgumentNullException(nameof(service)); }
            if (setupAction is null) { throw new ArgumentNullException(nameof(setupAction)); }
            var opt = new AlibabaOptions();
            setupAction(opt);
            service.Configure((AlibabaOptions options) => { 
                options.AccessKeyId =  opt.AccessKeyId; 
                options.AccessKeySecret = opt.AccessKeySecret;
                options.Format = opt.Format;
                options.RegionId = opt.RegionId;
                options.BaseAddressUrl = opt.BaseAddressUrl;
                options.Version = opt.Version;
            });
            service.AddHttpClient(typeof(AlibabaService).FullName, client =>
            {
                client.BaseAddress = new Uri(opt.BaseAddressUrl);
                client.DefaultRequestHeaders.UserAgent.ParseAdd("OT.Sms");
            });
            service.TryAddSingleton<AlibabaService>();
            return service;
        }
        /// <summary>腾讯短信服务</summary>
        public static IServiceCollection AddTencentSmsService(this IServiceCollection service, Action<TencentOptions> setupAction)
        {
            if (service == null)
                throw new ArgumentNullException(nameof(service));
            if (setupAction == null)
                throw new ArgumentNullException(nameof(setupAction));
            var opt = new TencentOptions();
            setupAction(opt);
            service.Configure((TencentOptions options) => { options = opt; });
            service.AddHttpClient(typeof(TencentService).FullName, client =>
            {
                client.BaseAddress = new Uri(opt.BaseAddressUrl);
                client.DefaultRequestHeaders.Accept.ParseAdd("application/json; charset=utf-8");
                client.DefaultRequestHeaders.UserAgent.ParseAdd("OT.Sms");
            });
            service.TryAddSingleton<TencentService>();
            return service;
        }
    }
}
